<?php
namespace CountLike\Controller;
use Common\Controller\CountLikeController;
class IndexController extends CountLikeController {


    public function __construct()
    {
        $sessionid = 'PHPSESSID='.$this->getSessionId();

        $getsessionid = $_SERVER['HTTP_COOKIE'];
        if ($sessionid!=$getsessionid){
            $this->returnData('','状态已过期请重新授权',400);
        }
    }

    /**
     *  获取基本信息
     */
    public function getinfo(){

        $member_id = I('post.member_id','','int');
        $appid = I('post.appid','','htmlspecialchars');

        if (!$member_id){
            $this->returnData('','参数错误','401');
        }

        $info = M('countlike_member')->field('nickname,avatarurl,money,rank,rankname')->where(array('countlike_member_id'=>$member_id))->find();

        $info['rank'] = (int)$info['rank'];


        $info['count'] = M('countlike_rank')->sum('nums');
        $where['rank'] = array('elt', $info['rank']);
        $info['nowcount'] = M('countlike_rank')->where($where)->sum('nums');

        $info['shengxia'] = $info['count']-$info['nowcount']; //剩余关数

        $info['countrank'] = 11; //所有等级

        $data['info'] = $info; //个人信息

        //规则
        $data['rule'] = array('每日签到获得1万金币，连续签到获得更多金币','每次答题正确获得1千金币，成功晋级获得1千金币','每次进入答题闯关消耗1万金币','每天可以分享到不同的群，有效分享将获得4万金币/次');


        $this->returnData($data);

    }

    /**
     * 挑战页面
     */
    public function getquestion()
    {
        $member_id      =   I('post.member_id','','int');
        $appid          =   I('post.appid','','htmlspecialchars');
        $go_on          =   I('post.go_on','','int');               //继续挑战

        if (empty($member_id) || empty($appid))
        {
            $this->returnData('','非法请求',401);
        }

        $field  =   array('countlike_member_id','money','rank','rankname','rank_status','number');
        $data['memebr_data']    =   M('countlike_member')->where(array('countlike_member_id'=>$member_id))->field($field)->find();
        $rule                   =   $this->get_rule();
        $data['enough']         =   1;  //金币是否充足
        $data['next_rank']      =   array();

        if (!$data['memebr_data'])
        {
            $this->returnData('','用户不存在',401);
        }

        if ($data['memebr_data']['money'] < $rule['resurgence'])
        {
            $data['enough'] =   0;
            $this->returnData($data,'金币不足，请分享群获得更多机会！',401);
        }

        $rang_id    =   0;
        switch ($data['memebr_data']['rank_status'])
        {
            case 0:
                $rang_id    =   $data['memebr_data']['rank'];
                break;

            case 1:
                $rang_id    =   $data['memebr_data']['rank'];
                break;

            case -1:
                $rang_id    =   $data['memebr_data']['rank'];
                break;
        }

        $next_rang_id       =     $rang_id + 1;

        $rank_all           =     $this->get_rank();

        $total_rank         =     count($rank_all);

        $data['total_rank'] =     $total_rank;

        if ( $next_rang_id >= $data['total_rank'] || $rang_id >= $data['total_rank'])
        {
            $rang_id        =     $data['total_rank'];
            $next_rang_id   =     $data['total_rank'];
        }

        $data['rang']       =     $this->get_rank($rang_id);
        $next_rank          =     $this->get_rank($next_rang_id);
        $data['next_name']  =     $next_rank['rankname'];

        if(empty($data['rang']))
        {
            $this->returnData('','非法请求',401);
        }

        $data['questions_data'] =   $this->get_question($rang_id,$data['rang']['nums']);

        //如果是复合答题，就要减去相应的金额
        if ($data['questions_data'] && $data['memebr_data']['rank_status'] == -1 || empty($go_on) || $go_on <= 0)
        {
            $update_data['money']   =   $data['memebr_data']['money'] - $rule['resurgence'];
            $update_data['number']  =   $data['memebr_data']['number']   +   1;
            $result = M('countlike_member')->where(array('countlike_member_id'=>$member_id))->data($update_data)->save(); // 根据条件保存修改的数据

            if ($result)
            {
                $data['memebr_data']['money']   =   $data['memebr_data']['money'] - $rule['resurgence'];
            }
            else
            {
                $this->returnData('','系统异常',401);
            }

        }

        $this->returnData($data);
    }

    /**
     * 挑战结果
     */
    public function challenge()
    {
        $member_id      =   I('post.member_id','','int');
        $appid          =   I('post.appid','','htmlspecialchars');
        $result         =   I('post.result','','int'); //挑战结果   1 和-1
        $client_rank    =   I('post.rank','','int');   //挑战的等级

        if(empty($member_id) || empty($appid) || empty($result) || empty($client_rank))
        {
            $this->returnData('','系统异常',401);
        }

        $field  =   array('countlike_member_id','money','rank','rankname','rank_status','answer_num');
        $data['memebr_data']    =   M('countlike_member')->where(array('countlike_member_id'=>$member_id))->field($field)->find();

        if (!$data['memebr_data'])
        {
            $this->returnData('','用户不存在',401);
        }

        if ($client_rank != $data['memebr_data']['rank'])
        {
            $this->returnData('','非法请求,你已经不该等级了',401);
        }

        $rule                   =   $this->get_rule();

        //挑战成功
        if ($result > 0)
        {
            $rank_id                            =   $data['memebr_data']['rank'];
            $rank_data                          =   $this->get_rank($data['memebr_data']['rank']);
            $data['memebr_data']['answer_num']  =   $data['memebr_data']['answer_num'] + 1;
            $rank_all           =     $this->get_rank();
            $total_rank         =     count($rank_all);
            $data['total_rank'] =     $total_rank;

            //如果答完整套题，就升级
            if($data['memebr_data']['answer_num'] >= $rank_data['nums'])
            {
                if ($data['total_rank'] == $client_rank)
                {
                    $rank_data                  =   $this->get_rank($data['total_rank']);
                    $update_data['rank']        =   $data['total_rank'];
                }
                else
                {
                    $rank_data                  =   $this->get_rank($data['memebr_data']['rank'] + 1);
                    $update_data['rank']        =   $data['memebr_data']['rank'] + 1;
                }

                $update_data['money']       =   $data['memebr_data']['money'] + $rank_data['money'] + $rule['answer'];    //挑战成功会额外加上奖励积分
                $update_data['rankname']    =   $rank_data['rankname'];

                $update_data['answer_num']  =   0;
                $update_data['rank_status'] =   1;  //0表示是没做题目，1表示挑战成功，-1表示挑战失败 （主要用于扣除复活积分的）

                M('countlike_member')->where(array('countlike_member_id'=>$member_id))->data($update_data)->save(); // 根据条件保存修改的数据

                $msg['money']       =   $update_data['money'];
                $msg['rankname']    =   $rank_data['rankname']; //普升失败的级别名称
                $msg['cut_money']   =   0;      //复活需要消耗的钱
                $msg['chance']      =   1;      //复活机会 0表示没有机会
                $msg['succeed']     =   1;      //挑战成功
                $msg['finish']      =   1;      //过关
            }
            else
            {
                $rank_data                  =   $this->get_rank($data['memebr_data']['rank'] + 1);
                $update_data['money']       =   $data['memebr_data']['money'] + $rule['answer'];
                $update_data['answer_num']  =   $data['memebr_data']['answer_num'];

                M('countlike_member')->where(array('countlike_member_id'=>$member_id))->data($update_data)->save(); // 根据条件保存修改的数据

                $msg['money']       =   $update_data['money'];
                $msg['rankname']    =   null;   //普升失败的级别名称 (答题中不返回)
                $msg['cut_money']   =   0;      //复活需要消耗的钱
                $msg['chance']      =   1;      //复活机会 0表示没有机会
                $msg['succeed']     =   1;      //挑战成功
                $msg['finish']      =   2;      //继续答题
            }

            $this->returnData($msg);
        }
        else
        {
            //挑战失败
            $rank_id                    =   $data['memebr_data']['rank'] +  1;
            $rank_data                  =   $this->get_rank($rank_id);
            $update_data['answer_num']  =   0;
            $update_data['rank_status'] =   -1;
            M('countlike_member')->where(array('countlike_member_id'=>$member_id))->data($update_data)->save(); // 根据条件保存修改的数据

            $msg['money']       =   $data['memebr_data']['money'];
            $msg['rankname']    =   $rank_data['rankname']; //普升失败的级别名称
            $msg['cut_money']   =   $rule['resurgence'];    //复活需要消耗的钱
            $msg['succeed']     =   0;                      //挑战失败
            $msg['finish']      =   0;                      //不过关

            if ($data['memebr_data']['money'] < $rule['resurgence'])
            {
                $msg['chance']  =   0;      //复活机会 0表示没有机会
            }
            else
            {
                $msg['chance']  =   1;      //复活机会 0表示没有机会
            }

            $this->returnData($msg,'金币不足，请分享群获得更多机会！',200);
        }


    }

    /**
     * 分享模板
     */
    public function sharetem(){

        $appid = I('post.appid','','htmlspecialchars');

        $data = M('countlike_sharetem')->find();
//        $data = array(
//            'title'=>'[有人@我]你有一张毕业证等待领取，点击领取',
//            'imgsrc'=>'',
//        );

        $this->returnData($data);

    }

    /**
     * 微信分享记录
     */
    public function sharerecord(){

        $member_id = I('post.member_id','','int');

        $encryptedData = $_POST['encryptedData'];
        $iv = $_POST['iv'];
        $appid = I('post.appid','','htmlspecialchars');

        if (!$member_id){
            $this->returnData('','参数错误',401);
        }

        $setinfo =$this->get_rule();

        $setinfo['sharegroup'] = (int)$setinfo['sharegroup'];

        if (!$encryptedData||!$member_id||!$iv){
            $this->returnData('','参数错误',401);
        }


        $info = M('countlike_member')->field('appid,session_key')->where(array('countlike_member_id'=>$member_id))->find();

        $appid = $info['appid'];
        $sessionkey = $info['session_key'];
        //解析openGId
        $openGId = $this->getopenGId($appid,$sessionkey,$encryptedData,$iv);

        if ($openGId=='-1'){
            $this->returnData('','分享失败',100);
        }

        $time = date('Y-m-d',time());

        $where['sharetime'] = $time;
        $where['countlike_member_id'] = $member_id;
        $where['opengid'] = $openGId;
        $where['appid'] = $appid;

        $record = M('countlike_wechat_group')->where($where)->getField('sharenum'); //判断是否已分享

        //如果分享超过2次则自增分享次数然后返回
        if ($record){
            M('countlike_wechat_group')->where($where)->setInc('sharenum');

            $this->returnData(array('repetition'=>'out'),'今天该群已分享',201);
        }

        if (!$record||empty($record)){
            //如果没分享过则插入，用户增加金币
            $add = array(
                'opengid'=>$openGId,
                'sharetime'=>$time,
                'sharenum'=>1,
                'countlike_member_id'=>$member_id,
                'appid'=>$appid,
            );

            M('countlike_wechat_group')->data($add)->add();
            M('countlike_member')->where(array('countlike_member_id'=>$member_id))->setInc('money',$setinfo['sharegroup']);

            $mymoney =  M('countlike_member')->where(array('countlike_member_id'=>$member_id))->getField('money');

            $data['money'] = $mymoney;
            $data['repetition'] = 'no';
            $this->returnData($data,'分享成功',200);
        }
    }


    /**
     * 广告
     */
    public function advertising(){

        $appid = I('post.appid','','htmlspecialchars');

        $data = M('countlike_appshow')->field('content,title',true)->where(array('isshow'=>'1'))->select();

        foreach ($data as $key=>$val){
            $data[$key]['logo'] = $this->url.$data[$key]['logo'];
            $data[$key]['index'] = $key;
        }

        $this->returnData($data);
    }


    /**
     * 历史成就
     */

    public function history(){

        $appid = I('post.appid','','htmlspecialchars');
        $member_id = I('post.member_id','','int');

        if (!$member_id){
            $this->returnData('','非法请求','401');
        }

        $myrank = M('countlike_member')->field('nickname,avatarurl,rank,rankname')->where(array('countlike_member_id'=>$member_id))->find();

        $allrank = M('countlike_rank')->field('rank,rankname')->order('rank asc')->select();

        //$allrank = $this->get_rank();
        foreach ($allrank as $key=>$val){

            $allrank[$key]['clear'] = 'yes';
            // $allrank[$key]['imgsrc'] = $this->url.$allrank[$key]['imgsrc'];
            if ($val['rank']>$myrank['rank']){ //判断是否解锁
                $allrank[$key]['clear'] = 'no';
            }

        }

        $data['allrank'] = $allrank;
        $data['myrank'] = $myrank;

        $this->returnData($data);


    }

    /**
     * 好友关联
     */
    public function friendsassociated(){

        $uid = I('post.my_member_id','','int');
        $coupling_uid = I('post.coupling_member_id','','int');
        $appid = I('post.appid','','htmlspecialchars');

        if ($uid==""||$coupling_uid==""){
            $this->returnData('','参数不能为空',401);
        }

        if ($uid==$coupling_uid){
            $this->returnData('','自己不用关联自己',100);
        }


        $where['my_member_id']=$uid;
        $where['coupling_member_id']=$coupling_uid;
        $where['appid'] = $appid;

        $where1['my_member_id']=$coupling_uid;
        $where1['coupling_member_id']=$uid;
        $where1['appid'] = $appid;

        $relevancy = M('countlike_relationship')->field('countlike_relationship_id')->where($where)->find();

        $relevancy1 = M('countlike_relationship')->field('countlike_relationship_id')->where($where1)->find();
        //判断是否已关联(有待优化)
        if ($relevancy||$relevancy1){
            $this->returnData('','已关联',200);
        }

        $data = array(
            'my_member_id'=>$uid,
            'coupling_member_id' =>$coupling_uid,
            'appid'=>$appid,
            'createtime' =>time(),
        );

        $insert = M('countlike_relationship')->data($data)->add();

        if ($insert){
            $this->returnData('','关联成功',200);
        }else{
            $this->returnData('','关联失败',100);
        }

    }

    /**
     * 排行
     */
    public function rank(){

        $member_id = I('post.member_id','','int');
        $state = I('post.state','1','int');
        $appid = I('post.appid','','htmlspecialchars');

        if (!$member_id||!$state){
            $this->returnData('','非法操作',401);
        }
        //世界排行
        if ($state=='1'){
            $rank = $this->getcacherank();
            $this->returnData($rank);
        }
        //好友排行
        if ($state=='2'){

            $where['my_member_id'] = $member_id;


            $coupling_uids = M('countlike_relationship')->where($where)->getField('coupling_member_id',true);
            if (empty($coupling_uids)){
                $coupling_uids = array();
            }
            $coupling_uids[] = $member_id;


            $uids = M('countlike_relationship')->where(array('coupling_member_id'=>$member_id))->getField('my_member_id',true);
            if (empty($uids)){
                $uids = array();
            }

            $ids = array_unique(array_merge($coupling_uids,$uids));//合并去重

            $where1['countlike_member_id'] = array('in',$ids);
            $rank = "";
            if ($ids){
                $rank = M('countlike_member')->field('nickname,avatarurl,money,rankname')->where($where1)->limit(30)->order('money desc')->select();

                foreach ($rank as $key=>$value){
                    $rank[$key]['money'] = $rank[$key]['money']/10000;
                    $rank[$key]['money'] = $rank[$key]['money'].'万金币';
                }

            }

            $this->returnData($rank,'成功','200');

        }



    }

    /**
     * 签到
     *  money           表示拥护当前的钱
     *  sign_status     表示签到状态 0签到失败，1签到成功，2已经签到过了
     */
    public function sign()
    {
        $member_id      =   I('post.member_id','','int');
        $appid          =   I('post.appid','','htmlspecialchars');

        if(empty($member_id) || empty($appid))
        {
            $this->returnData('','系统异常',401);
        }

        unset($where);
        $where_member['countlike_member_id']    =   $member_id;
        $field          =   array('countlike_member_id','signin_start','signin_num','money');
        $member_data    =   M('countlike_member')->where($where_member)->field($field)->find();
        $msg['sign_data']        =   $this->get_sign_config();

        if (! $member_data)
        {
            $msg['day']             =   0;
            $msg['money']           =   0;
            $msg['sign_status']     =   0;      //
            $this->returnData($msg,'非法请求！',401);
        }

        $where['countlike_member_id']   =   $member_id;
        $where['signin_time']           =   date("Y-m-d");
        $today_sign     =   M('countlike_signin')->where($where)->field('countlike_signin_id')->find();

        if ($today_sign)
        {
            $msg['day']             =   $member_data['signin_num'];
            $msg['money']           =   $member_data['money'];
            $msg['signin_money']    =   $this->get_sign_config($member_data['signin_num']);
            $msg['sign_status']     =   2;      //表示已经签到过了
            $this->returnData($msg,'你今天已经签到过了！',200);
        }
        else
        {
            //第一次签到或重新的周期开启签到
            if (empty($member_data['signin_start']) || empty($member_data['signin_num']) || $member_data['signin_num'] == 7)
            {
                $signin_data                        =   array();
                $signin_data['countlike_member_id'] =   $member_id;
                $signin_data['signin_time']         =   date("Y-m-d");
                $signin_data['signin_num']          =   1;
                $signin_data['appid']               =   $appid;
                $signin_data['creat_time']          =   time();
                $result     =   M('countlike_signin')->add($signin_data);
                M('countlike_member')->where(array('countlike_member_id'=>$member_id))->save(array('giveopportunity'=>'1')); //每天赠送机会
                unset($signin_data);
                if ($result)
                {
                    $update_data                =   array();
                    $update_data['money']       =   $member_data['money']   +   $this->get_sign_config(1);
                    $update_data['signin_start']=   date("Y-m-d");
                    $update_data['signin_num']  =   1;
                    $result     =    M('countlike_member')->where(array('countlike_member_id'=>$member_id))->data($update_data)->save(); // 根据条件保存修改的数据

                    if ($result)
                    {
                        $msg['day']             =   $update_data['signin_num'];
                        $msg['money']           =   $update_data['money'];
                        $msg['signin_money']    =   $this->get_sign_config(1);
                        $msg['sign_status']     =   1;      //签到成功

                        $this->returnData($msg,'签到成功！',200);
                    }
                }

                //能执行到这里的都是签到失败的
                $msg['day']             =   $member_data['signin_num'];
                $msg['money']           =   $member_data['money'];
                $msg['signin_money']    =   0;
                $msg['sign_status']     =   0;      //签到失败
                $this->returnData($msg,'签到失败！',200);
            }
            else
            {
                $where                          =   array();
                $where['countlike_member_id']   =   $member_id;
                $where['signin_time']           =   date("Y-m-d",strtotime("-1 day"));
                $yesterday_sign     =   M('countlike_signin')->where($where)->field('countlike_signin_id')->find();

                if($yesterday_sign)
                {
                    $signin_data                        =   array();
                    $signin_data['countlike_member_id'] =   $member_id;
                    $signin_data['signin_time']         =   date("Y-m-d");
                    $signin_data['signin_num']          =   1;
                    $signin_data['appid']               =   $appid;
                    $signin_data['creat_time']          =   time();
                    $result     =   M('countlike_signin')->add($signin_data);

                    if ($result)
                    {
                        $update_data                =   array();
                        $update_data['signin_num']  =   $member_data['signin_num'] + 1;
                        $update_data['money']       =   $member_data['money']   +   $this->get_sign_config($update_data['signin_num']);
                        $result     =    M('countlike_member')->where(array('countlike_member_id'=>$member_id))->data($update_data)->save(); // 根据条件保存修改的数据

                        if ($result)
                        {
                            $msg['day']             =   $update_data['signin_num'];
                            $msg['money']           =   $update_data['money'];
                            $msg['signin_money']    =   $this->get_sign_config($update_data['signin_num']);
                            $msg['sign_status']     =   1;      //签到成功
                            $this->returnData($msg,'签到成功！',200);
                        }
                    }

                }
                else
                {
                    //要是昨天没有签到，之前的签到都累积的没了，重新开始
                    $signin_data                        =   array();
                    $signin_data['countlike_member_id'] =   $member_id;
                    $signin_data['signin_time']         =   date("Y-m-d");
                    $signin_data['signin_num']          =   1;
                    $signin_data['appid']               =   $appid;
                    $signin_data['creat_time']          =   time();
                    $result     =   M('countlike_signin')->add($signin_data);
                    unset($signin_data);

                    if ($result)
                    {
                        $update_data                =   array();
                        $update_data['money']       =   $member_data['money']   +   $this->get_sign_config(1);
                        $update_data['signin_start']=   date("Y-m-d");
                        $update_data['signin_num']  =   1;
                        $result     =    M('countlike_member')->where(array('countlike_member_id'=>$member_id))->data($update_data)->save(); // 根据条件保存修改的数据

                        if ($result)
                        {
                            $msg['day']             =   $update_data['signin_num'];
                            $msg['money']           =   $update_data['money'];
                            $msg['signin_money']    =   $this->get_sign_config(1);
                            $msg['sign_status']     =   1;      //签到成功
                            $this->returnData($msg,'签到成功！',200);
                        }
                    }

                    //能执行到这里的都是签到失败的
                    $msg['day']             =   $member_data['signin_num'];
                    $msg['money']           =   $member_data['money'];
                    $msg['signin_money']    =   0;
                    $msg['sign_status']     =   0;      //签到失败
                    $this->returnData($msg,'签到失败！',200);
                }
            }
        }
    }

    /**
     * 存放模板消息
     */
    public function send()
    {
        $appid = I('post.appid','','htmlspecialchars');
        $touser = I('post.touser','','htmlspecialchars');
        $page = I('post.page','','htmlspecialchars');
        $form_id = I('post.form_id','','htmlspecialchars');
        $form_type = I('post.form_type','','htmlspecialchars');
        $secret = I('post.secret','','htmlspecialchars');
        $member_id = I('post.member_id','','int');
        $template_id = I('post.template_id','','htmlspecialchars');

        if ($touser==""||$form_id==""){
            $this->returnData('','参数错误','401');
        }

        $date = date('Y-m-d');
        $insert = array(
            'appid'=>$appid,
            'touser'=>$touser,
            'template_id'=>$template_id,
            'page'=>$page,
            'form_id'=>$form_id,
            'form_type'=>$form_type?$form_type:1,
            'status'=>'-1',
            'add_time'=>time(),
            'secret'=>$secret,
            'createtime'=>$date,
            'countlike_member_id'=>$member_id,
        );

        M('countlike_template_send')->data($insert)->add();
        $this->returnData('成功','200');

        $where['touser'] = $touser;
        $where['createtime'] = $date;
        $where['status'] = '-1';

        $ishave = M('countlike_template_send')->field('wxopen_template_send_id')->where($where)->find();

        if ($ishave){
            M('countlike_template_send')->where(array('wxopen_template_send_id'=>$ishave['wxopen_template_send_id']))->save($insert);
        }else{
            M('countlike_template_send')->data($insert)->add();
        }

        $this->returnData('成功','200');

    }

}